<template>
  <a-modal
    v-model:open="visible"
    title="分配维修工"
    @ok="handleAssign"
    @cancel="handleCancel"
    :confirm-loading="assignLoading"
    :ok-button-props="{ disabled: !selectedWorkerId }"
    width="1200px"
  >
    <div class="assign-worker-modal">
      <!-- 左右布局 -->
      <div class="assign-worker-layout">
        <!-- 左侧：手动选择 -->
        <div class="manual-section">
          <div class="section-header">
            <h3>手动选择维修工</h3>
          </div>
          <div class="manual-assign-content">
            <!-- 搜索和筛选 -->
            <div class="search-section">
              <div class="search-row">
                <a-input
                  v-model:value="searchKeyword"
                  placeholder="搜索维修工姓名或账号"
                  @change="handleSearch"
                  class="search-input"
                />
                <a-button type="primary" @click="handleSearch" class="search-button">
                  搜索
                </a-button>
              </div>
              <div class="filter-row">
                <a-select
                  v-model:value="skillFilter"
                  placeholder="按技能筛选"
                  class="skill-filter"
                  allow-clear
                  @change="handleSkillFilter"
                >
                  <a-select-option
                    v-for="category in categoryList"
                    :key="category.id"
                    :value="category.id"
                  >
                    {{ category.categoryName }}
                  </a-select-option>
                </a-select>
                <a-button @click="handleClearFilter" class="clear-button">
                  清空筛选
                </a-button>
              </div>
            </div>

            <!-- 维修工列表 -->
            <a-spin :spinning="loading" tip="正在加载维修工列表...">
              <div v-if="!loading && filteredWorkerList.length === 0" class="empty-state">
                <a-empty description="暂无可分配的维修工" />
              </div>

              <div v-else class="worker-list">
                <a-radio-group v-model:value="selectedWorkerId" class="worker-radio-group">
                  <div
                    v-for="worker in paginatedWorkerList"
                    :key="worker.userInfo.id"
                    class="worker-item"
                  >
                    <a-radio :value="worker.userInfo.id" class="worker-radio">
                      <div class="worker-info">
                        <div class="worker-name">{{ worker.userInfo.nickName }}</div>
                        <div class="worker-details">
                          <span class="worker-account">账号: {{ worker.userInfo.accountName }}</span>
                          <span class="worker-phone">电话: {{ worker.userInfo.phoneNumber }}</span>
                        </div>
                        <div class="worker-skills">
                          <a-tag
                            v-for="skill in worker.skills"
                            :key="skill.categoryId"
                            size="small"
                            color="blue"
                          >
                            {{ skill.categoryName }}
                          </a-tag>
                          <span v-if="worker.skills.length === 0" class="no-skills">暂无技能</span>
                        </div>
                      </div>
                    </a-radio>
                  </div>
                </a-radio-group>

                <!-- 分页 -->
                <div class="pagination-section" v-if="filteredWorkerList.length > pageSize">
                  <a-pagination
                    v-model:current="currentPage"
                    :total="filteredWorkerList.length"
                    :page-size="pageSize"
                    :show-size-changer="false"
                    :show-quick-jumper="false"
                    size="small"
                    @change="handlePageChange"
                  />
                </div>
              </div>
            </a-spin>
          </div>
        </div>

        <!-- 右侧：AI推荐 -->
        <div class="recommend-section">
          <div class="section-header">
            <h3>AI智能推荐</h3>
            <a-tag v-if="recommendLoading" color="processing">
              <template #icon>
                <a-spin size="small" />
              </template>
              分析中...
            </a-tag>
            <a-tag v-else-if="hasTriedRecommend && recommendedWorkers.length > 0" color="success">
              推荐完成
            </a-tag>
          </div>

          <div class="recommend-assign-content">
            <a-spin :spinning="recommendLoading" tip="正在分析推荐...">
              <!-- AI分析结果 -->
              <div v-if="aiResult && aiResult.success" class="ai-analysis-result">
                <div class="ai-analysis-card">
                  <div class="ai-analysis-header">
                    <span class="ai-icon">🤖</span>
                    <span class="ai-title">AI分析结果</span>
                    <div class="confidence-badge">
                      <span class="confidence-label">置信度</span>
                      <span class="confidence-value">{{ Math.round((aiResult.confidence || 0) * 100) }}%</span>
                    </div>
                  </div>
                  <div class="ai-analysis-content">
                    <p class="ai-reason">{{ aiResult.reason || '基于工单类别和维修工技能进行智能匹配' }}</p>
                  </div>
                </div>
              </div>

              <div v-if="!recommendLoading && recommendedWorkers.length === 0 && hasTriedRecommend" class="empty-state">
                <a-empty description="暂无推荐的维修工" />
              </div>

              <div v-else-if="recommendedWorkers.length > 0" class="recommended-worker-list">
                <div class="recommendation-title">
                  <span class="title-icon">⭐</span>
                  <span class="title-text">为您推荐 {{ recommendedWorkers.length }} 位维修工</span>
                </div>
                <a-radio-group v-model:value="selectedWorkerId" class="worker-radio-group">
                  <div
                    v-for="(worker, index) in recommendedWorkers"
                    :key="worker.id"
                    class="recommended-worker-item"
                    :class="{ 'top-recommendation': index === 0 && aiResult?.recommendedMaintenanceId === worker.id }"
                  >
                    <a-radio :value="worker.id" class="worker-radio">
                      <div class="worker-info">
                        <div class="worker-header">
                          <div class="worker-name-section">
                            <span class="rank-number">#{{ index + 1 }}</span>
                            <span class="worker-name">{{ worker.nickName }}</span>
                          </div>
                          <div class="worker-tags">
                            <a-tag
                              :color="index === 0 && aiResult?.recommendedMaintenanceId === worker.id ? 'red' : 'blue'"
                              size="small"
                              class="recommendation-tag"
                            >
                              {{ index === 0 && aiResult?.recommendedMaintenanceId === worker.id ? '🏆 最佳推荐' : '推荐' }}
                            </a-tag>
                          </div>
                        </div>
                        <div class="worker-details">
                          <div class="detail-item">
                            <span class="detail-label">账号:</span>
                            <span class="detail-value">{{ worker.accountName }}</span>
                          </div>
                          <div class="detail-item">
                            <span class="detail-label">电话:</span>
                            <span class="detail-value">{{ worker.phoneNumber }}</span>
                          </div>
                        </div>
                      </div>
                    </a-radio>
                  </div>
                </a-radio-group>
              </div>
            </a-spin>
          </div>
        </div>
      </div>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import { message } from 'ant-design-vue'
import { assignWorkOrder } from '@/api/workorder'
import { getAllMaintenanceWorkers, recommendMaintenanceWorkers } from '@/api/skill'
import { getCategoryList } from '@/api/category'
import type {
  WorkOrderAssignRequest,
  UserSkillSummaryResponse,
  RepairCategory,
  WorkOrderRecommendRequest,
  UserResponse,
  AiAssignmentResult
} from '@/types'

interface Props {
  open: boolean
  workOrderId?: number
}

interface Emits {
  (e: 'update:open', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const visible = ref(false)
const loading = ref(false)
const assignLoading = ref(false)
const recommendLoading = ref(false)
const workerList = ref<UserSkillSummaryResponse[]>([])
const recommendedWorkers = ref<UserResponse[]>([])
const categoryList = ref<RepairCategory[]>([])
const selectedWorkerId = ref<number>()
const hasTriedRecommend = ref(false)
const aiResult = ref<AiAssignmentResult | null>(null)

// 搜索和筛选
const searchKeyword = ref('')
const skillFilter = ref<number>()

// 分页
const currentPage = ref(1)
const pageSize = ref(5)

// 计算属性
const filteredWorkerList = computed(() => {
  let filtered = workerList.value

  // 按关键词搜索
  if (searchKeyword.value) {
    filtered = filtered.filter(worker =>
      worker.userInfo.nickName.includes(searchKeyword.value) ||
      worker.userInfo.accountName.includes(searchKeyword.value)
    )
  }

  // 按技能筛选
  if (skillFilter.value) {
    filtered = filtered.filter(worker =>
      worker.skills.some(skill => skill.categoryId === skillFilter.value)
    )
  }

  return filtered
})

const paginatedWorkerList = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredWorkerList.value.slice(start, end)
})

// 监听props.open变化
watch(() => props.open, (newVal) => {
  visible.value = newVal
  if (newVal) {
    resetModal()
    fetchWorkerList()
    fetchCategories()
    // 自动获取AI推荐
    fetchRecommendations()
  }
})

// 监听visible变化，同步到父组件
watch(visible, (newVal) => {
  emit('update:open', newVal)
})

// 重置弹窗状态
const resetModal = () => {
  selectedWorkerId.value = undefined
  searchKeyword.value = ''
  skillFilter.value = undefined
  currentPage.value = 1
  recommendedWorkers.value = []
  hasTriedRecommend.value = false
  aiResult.value = null
}

// 获取维修工列表（带技能信息）
const fetchWorkerList = async () => {
  try {
    loading.value = true
    const response = await getAllMaintenanceWorkers()

    if (response.code === 0) {
      workerList.value = response.data || []
    } else {
      message.error('获取维修工列表失败')
    }
  } catch (error) {
    console.error('获取维修工列表失败:', error)
    message.error('获取维修工列表失败')
  } finally {
    loading.value = false
  }
}

// 获取维修类别列表（只获取启用的）
const fetchCategories = async () => {
  try {
    const response = await getCategoryList({
      pageSize: 100,
      isActive: 1 // 只获取启用的类别
    })
    if (response.code === 0) {
      categoryList.value = response.data?.records || []
    }
  } catch (error) {
    console.error('获取维修类别失败:', error)
  }
}

// 获取AI推荐
const fetchRecommendations = async () => {
  if (!props.workOrderId) {
    message.warning('工单信息不完整')
    return
  }

  try {
    recommendLoading.value = true
    hasTriedRecommend.value = true
    const request: WorkOrderRecommendRequest = {
      workOrderId: props.workOrderId,
      count: 5
    }

    const response = await recommendMaintenanceWorkers(request)
    if (response.code === 0 && response.data) {
      aiResult.value = response.data.aiResult
      recommendedWorkers.value = response.data.recommendedWorkers || []

      if (recommendedWorkers.value.length === 0) {
        message.info('暂无推荐的维修工')
      } else {
        message.success(`AI推荐了 ${recommendedWorkers.value.length} 位维修工`)
      }

      // 如果AI有错误信息，显示警告
      if (aiResult.value && !aiResult.value.success && aiResult.value.errorMessage) {
        message.warning(`AI分析提示: ${aiResult.value.errorMessage}`)
      }
    } else {
      message.error(response.message || '获取推荐失败')
    }
  } catch (error) {
    console.error('获取推荐失败:', error)
    message.error('获取推荐失败')
  } finally {
    recommendLoading.value = false
  }
}



// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
}

// 技能筛选处理
const handleSkillFilter = () => {
  currentPage.value = 1
}

// 清空筛选
const handleClearFilter = () => {
  searchKeyword.value = ''
  skillFilter.value = undefined
  currentPage.value = 1
}

// 分页处理
const handlePageChange = (page: number) => {
  currentPage.value = page
}

// 确认分配
const handleAssign = async () => {
  if (!selectedWorkerId.value || !props.workOrderId) {
    message.warning('请选择要分配的维修工')
    return
  }

  try {
    assignLoading.value = true
    const assignRequest: WorkOrderAssignRequest = {
      workOrderId: props.workOrderId,
      handlerId: selectedWorkerId.value
    }

    const response = await assignWorkOrder(assignRequest)
    if (response.code === 0) {
      message.success('分配成功')
      visible.value = false
      emit('success')
    } else {
      message.error(response.message || '分配失败')
    }
  } catch (error) {
    console.error('分配维修工失败:', error)
    message.error('分配失败，请重试')
  } finally {
    assignLoading.value = false
  }
}

// 取消分配
const handleCancel = () => {
  visible.value = false
}
</script>

<style scoped>
.assign-worker-modal {
  max-height: 600px;
}

.assign-worker-layout {
  display: flex;
  gap: 24px;
  min-height: 500px;
}

.manual-section,
.recommend-section {
  flex: 1;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  padding: 16px;
  background-color: #fafafa;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e8e8e8;
}

.section-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #262626;
}

.search-section {
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.search-row,
.filter-row {
  display: flex;
  gap: 8px;
  margin-bottom: 8px;
  align-items: center;
}

.search-input {
  flex: 1;
}

.search-button {
  flex-shrink: 0;
}

.skill-filter {
  flex: 1;
}

.clear-button {
  flex-shrink: 0;
}

.manual-assign-content,
.recommend-assign-content {
  min-height: 400px;
  background-color: white;
  border-radius: 6px;
  padding: 12px;
}

.worker-list {
  max-height: 350px;
  overflow-y: auto;
  padding: 8px 0;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}

.worker-radio-group {
  width: 100%;
}

.worker-item,
.recommended-worker-item {
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.worker-item:last-child,
.recommended-worker-item:last-child {
  border-bottom: none;
}

.worker-radio {
  width: 100%;
  display: flex;
  align-items: flex-start;
}

.worker-radio :deep(.ant-radio) {
  margin-top: 2px;
}

.worker-info {
  margin-left: 8px;
  flex: 1;
}

.worker-name {
  font-size: 16px;
  font-weight: 500;
  color: #262626;
  margin-bottom: 4px;
}

.worker-details {
  display: flex;
  flex-direction: column;
  gap: 2px;
  margin-bottom: 8px;
}

.worker-account,
.worker-phone {
  font-size: 14px;
  color: #8c8c8c;
}

.worker-skills {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.no-skills {
  color: #999;
  font-size: 12px;
}

.pagination-section {
  text-align: center;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

.ai-analysis-result {
  margin-bottom: 16px;
}

.ai-analysis-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  padding: 16px;
  color: white;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.ai-analysis-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
}

.ai-icon {
  font-size: 20px;
}

.ai-title {
  font-weight: 600;
  font-size: 16px;
  flex: 1;
}

.confidence-badge {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 20px;
  padding: 4px 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.confidence-label {
  font-size: 12px;
  opacity: 0.9;
}

.confidence-value {
  font-weight: 600;
  font-size: 14px;
}

.ai-analysis-content {
  margin-top: 8px;
}

.ai-reason {
  margin: 0;
  font-size: 14px;
  line-height: 1.5;
  opacity: 0.95;
}

.recommendation-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  padding: 12px;
  background: linear-gradient(90deg, #f0f9ff 0%, #e0f2fe 100%);
  border-radius: 8px;
  border-left: 4px solid #0ea5e9;
}

.title-icon {
  font-size: 18px;
}

.title-text {
  font-weight: 600;
  color: #0369a1;
}

.recommended-worker-list {
  max-height: 350px;
  overflow-y: auto;
}

.worker-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.worker-name-section {
  display: flex;
  align-items: center;
  gap: 8px;
}

.rank-number {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  background: #f0f0f0;
  border-radius: 50%;
  font-size: 12px;
  font-weight: 600;
  color: #666;
}

.worker-tags {
  display: flex;
  gap: 4px;
}

.recommendation-tag {
  font-weight: 500;
}

.worker-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.detail-label {
  font-size: 12px;
  color: #8c8c8c;
  min-width: 40px;
}

.detail-value {
  font-size: 13px;
  color: #262626;
}

.top-recommendation {
  border: 2px solid #ff4d4f;
  border-radius: 12px;
  background: linear-gradient(135deg, #fff2f0 0%, #ffebe8 100%);
  box-shadow: 0 2px 8px rgba(255, 77, 79, 0.2);
}

.top-recommendation .worker-radio {
  padding: 12px;
}

.top-recommendation .rank-number {
  background: #ff4d4f;
  color: white;
}
</style>
